<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import type { IOrder } from '@/types/order'
import { getOrderDetailAPI } from '@/services/payment'
import { testnosifyAPI, balancePayAPI } from '@/services/pay'

import { useMemberStore } from '@/stores'
import { unifiedorderAPI } from '@/services/order'
const { getUserInfo } = useMemberStore()

const { safeAreaInsets } = uni.getSystemInfoSync()
const selectedMethod = ref(null as any)
const orderInfo = ref({} as IOrder)
const query = defineProps<{
  orderId: number
  orderPaymentId: number
}>()
const selectMethod = (tag: number) => {
  selectedMethod.value = tag
}

const detailOrderRequest = async () => {
  const res = await getOrderDetailAPI({
    orderId: query.orderId,
  })
  orderInfo.value = res.data
}

const sumbitHandler = async () => {
  if (selectedMethod.value === 0) {
    const unifiedOrderRes = await unifiedorderAPI({
      orderPaymentId: query.orderPaymentId,
      userId: getUserInfo()?.id,
      openid: getUserInfo()?.openid,
    })

    const payParamsRes = await testnosifyAPI({
      tradeNo: unifiedOrderRes.data.prepayId || '',
    })
    console.log('付款成功 ' + payParamsRes)
  }
  if (selectedMethod.value === 4) {
    const payParamsRes = await balancePayAPI({
      orderPaymentId: query.orderPaymentId,
      userId: getUserInfo()?.id,
    })
    console.log('付款成功 ' + payParamsRes)
  }
  // 注释掉
  // uni.requestPayment({
  //   provider: 'wxpay',
  //   orderInfo: {
  //     appid: payParamsRes.data.appId, // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
  //     timeStamp: payParamsRes.data.timeStamp,
  //     nonceStr: payParamsRes.data.nonceStr,
  //     package: payParamsRes.data.packageValue,
  //     sign: payParamsRes.data.paySign,
  //     partnerid: payParamsRes.data.mchKey, // 微信支付商户号
  //     prepayid: payParamsRes.data.prepayId, // 统一下单订单号
  //   },
  //   success(res) {
  //     console.log(res)
  //   },
  //   fail(e) {
  //     console.log('支付失败/取消:', e)

  //     // 判断失败原因
  //     if (e.errMsg === 'requestPayment:fail cancel') {
  //       // 用户主动取消支付
  //       console.log('用户取消了支付')
  //       uni.showToast({
  //         title: '支付已取消',
  //         icon: 'none',
  //       })
  //       // 可以选择留在当前页面，或者进行其他提示
  //     } else if (e.errMsg.includes('requestPayment:fail')) {
  //       // 其他支付失败（如签名错误、网络问题、余额不足等）
  //       console.error('支付失败:', e.errMsg)
  //       uni.showToast({
  //         title: '支付失败: ' + e.errMsg,
  //         icon: 'none',
  //       })
  //     } else {
  //       // 更罕见的错误
  //       console.error('支付异常:', e)
  //       uni.showToast({
  //         title: '支付异常',
  //         icon: 'none',
  //       })
  //     }
  //   },
  // })
}

onLoad(() => {
  detailOrderRequest()
})
</script>
<template>
  <view class="payment-page" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
    <view class="main">
      <!-- 支付金额 -->
      <view class="header">
        <text>支付金额</text>
        <text>￥{{ orderInfo.finalAmount }}</text>
        <template v-for="item in orderInfo.orderItemsList" :key="item.id">
          <text class="detail-name">{{ item.goodsName }} x {{ item.quantity }}</text>
          <!-- <text v-if="item.isSetmeal === 0">{{ item.goodsName }} x {{ item.quantity }}</text>
          <text v-else>{{ item.description }}</text> -->
        </template>
      </view>

      <!-- 支付方式 -->
      <view class="payment-methods">
        <view class="method" @click="selectMethod(0)">
          <text class="iconfont icon-weixin"></text>
          <text>微信支付</text>
          <text
            class="iconfont icon-gouxuan-xuanzhong-yuankuang"
            v-if="selectedMethod === 0"
          ></text>
          <text class="iconfont icon-gouxuan3" v-else></text>
        </view>
        <view class="method" @click="selectMethod(4)">
          <text class="iconfont icon-dingdanzhuangtai-baojia"></text>
          <text>余额支付</text>
          <text
            class="iconfont icon-gouxuan-xuanzhong-yuankuang"
            v-if="selectedMethod === 4"
          ></text>
          <text class="iconfont icon-gouxuan3" v-else></text>
        </view>
      </view>

      <!-- 金额明细 -->
      <view class="details">
        <view class="item real">
          <text>商品金额</text>
          <text>¥{{ orderInfo.totalAmount }}</text>
        </view>
        <view class="item discount">
          <text>优惠金额</text>
          <text>-¥{{ orderInfo.discountAmount }}</text>
        </view>
        <view class="item total">
          <text>总计金额</text>
          <text>¥{{ orderInfo.finalAmount }}</text>
        </view>
      </view>
    </view>
    <button @click="sumbitHandler()" class="pay-button">确认支付</button>
  </view>
</template>

<style lang="scss">
@import '@/styles/variables.scss';
page {
  height: 100%;
  overflow: hidden;
  background-color: $background-color;
}
.payment-page {
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  height: 100%;
  .main {
    flex: 1;
  }

  .header {
    background-color: #fff;
    text-align: center;
    padding: $medium-padding;
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 20rpx;

    text:nth-child(1) {
      font-size: $font-large-size;
      font-weight: $font-medium-weight;
      color: $good-font-title-color;
    }

    text:nth-child(2) {
      margin: $smallx-padding 0;
      font-size: 76rpx;
      color: #2e7d32;
      font-weight: $font-bold-weight;
    }

    .detail-name {
      font-size: $font-size;
      color: $good-font-con-color;
      font-weight: $font-weight;
    }
  }

  .payment-methods {
    border: 1px solid $border-color;
    margin-bottom: 20rpx;
    border-radius: 10rpx;
    .method {
      display: flex;
      align-items: center;
      padding: 20rpx;

      background-color: #fff;
      color: $color;

      text:nth-child(1) {
        font-size: 40rpx;
        font-weight: $font-medium-weight;
        margin-right: 20rpx;
      }

      text:nth-child(2) {
        flex: 1;
        font-size: $font-medium-size;
        color: $good-font-title-color;
        font-weight: $font-weight;
      }
    }
  }

  .details {
    border: 1px solid $border-color;
    border-radius: 10rpx;
    padding: 20rpx;
    margin-bottom: 20rpx;
    background-color: #fff;
    .item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 20rpx;
      text {
        font-size: 32rpx;
        color: #4b5563;
        font-weight: 400;
      }

      text:nth-child(1) {
        font-weight: $font-regular-weight;
      }
    }
    .discount {
      text:nth-child(2) {
        color: #ff4b4b;
      }
    }
    .total {
      text:nth-child(2) {
        font-size: 40rpx;
        font-weight: $font-medium-weight;
        color: #333333;
      }
    }
  }

  .pay-button {
    background-color: $color;
    color: white;
    border: none;
    height: 104rpx;
    line-height: 104rpx;
    border-radius: 52rpx;
    width: auto;
    font-size: $font-medium-size;
    margin: 0 60rpx;
  }
}
</style>
